<?php

namespace App\Livewire;

use App\Enums\BorrowStatus;
use App\Models\Book;
use App\Models\BorrowRecord;
use App\Models\Order;
use App\Models\User;
use Carbon\Carbon;
use Filament\Notifications\Notification;
use Illuminate\Database\Eloquent\Collection;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Lazy;
use Livewire\Component;
use Livewire\WithPagination;

#[Lazy]
class BookPage extends Component
{
    use WithPagination;
    public Book $book;
    public Collection $recommend_books;

    private string $error  = "操作失败";
    public function mount(Book $book)
    {
        $this->book = $book;
        $this->book->increment('views');
        $this->getRecommendBooks();

    }

    #[Computed]
    public function isRead()
    {
        return auth('frontend')->user()?->benefit()->where('name','在线阅读')->exists();
    }
    #[Computed]
    public function hasBorrowed()
    {
      return  $this->checkBorrowRecord();
    }
    public function borrowBook()
    {

        if (!$this->validateBorrow()){
            $this->dispatch('error',$this->error);
            return;
        }

        $this->dispatch('borrowBook');

        $this->dispatch('success','借阅成功');

    }

    private function validateBorrow()
    {
        if (!auth('frontend')->check()){
              $this->error = "请先登录";
               return false;
        }
        if ($this->book->quantity == 0){

            $this->error = "已经被借完了";
            return false;
        }
        if (!$this->book->status){

            $this->error = "已经被下架了";
            return false;
        }
        if (!$this->canBorrow){
            $this->error = "您没有借阅书籍的权限,请联系管理员";
            return false;
        }
        if ($this->hasBorrowed()){

            $this->error = "请不要重复借阅";
            return false;
        }
        if (!$this->borrowHandle()){
            $this->error = "借阅失败";
            return false;

        }
        $user = auth('frontend')->user();
        Notification::make()
            ->title("借阅申请")
            ->body("{$user->name} 申请借阅 【{$this->book->title}】!,请在后台审核")
            ->sendToDatabase(User::all());
        return true;
    }

    #[Computed]
    public function canBorrow()
    {
        if (auth('frontend')->user()?->benefit()->where('name','借阅书籍')->exists())
        {
            return true;
        }
        if (auth('frontend')->user()?->mobile &&
            auth('frontend')->user()?->is_active &&
            auth('frontend')->user()?->borrowRecord()->where('created_at','>',Carbon::now()->subMonths())->count() < 3)
        {
            return true;
        }
        return  false;
    }

    public function borrowHandle(): \Illuminate\Database\Eloquent\Model
    {
      $this->book->decrement('quantity');
      return  $this->book->borrowRecord()->create([
            'member_id' => auth('frontend')->id(),
            'returned' => BorrowStatus::STATUS_APPLY,
            //'borrow_date'=>Carbon::now()
        ]);
    }

    public function buyBook($num)
    {
        if (!auth('frontend')->check()) {
            return $this->dispatch('error','请先登录');
        }
        if (!$num) {
            return $this->dispatch('error','数量无效');
        }
        if ($this->book->quantity < $num) {
            return $this->dispatch('error','下单失败,库存不足');
        }
        $this->book->decrement('quantity');
        Order::create([
            'book_id'=>$this->book->id,
            'category_id'=>$this->book->category_id,
            'user_id'=>auth('frontend')->user()->id,
            'price'=>$this->book->price * $num,
            'status'=>1,
            'num'=>$num
        ]);
        return $this->dispatch('success','下单成功');

    }

    public function checkBorrowRecord()
    {
        if (!auth('frontend')->check()){
                return false;
        }

        return auth('frontend')->user()->hasBorrowBook($this->book->id);
    }

    public function render()
    {
        return view('livewire.book-page',
            [
                'chapters' => $this->getPageData(),
            ])
            ->layoutData([
                'category' => $this->book->category,
            ]);
    }



    private function getRecommendBooks(): void
    {
        $this->recommend_books = Book::query()
            ->where('category_id', $this->book->category_id)
            ->where('id', '<>', $this->book->id)
            ->inRandomOrder()
            ->limit(4)
            ->get();
    }

    private function getPageData()
    {
        $query = $this->book->chapters()->orderBy('id', 'asc');

        return $this->isRead() ?$query->paginate(20) : $query->limit(10)->get();
    }
}
